import axios from 'axios';
import qs from 'qs';
import { withRouter } from 'react-router';

const DOMAIN = 'http://qiandao.oo/api';


axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      browserHistory.push('/login')
    }
  }
);

const http = {
  token: '',
  getToken: function () {
    if (this.token) {
      return this.token;
    }
    this.token = localStorage.getItem('token')
    if (this.token) {
      return this.token;
    }
    this.token = sessionStorage.getItem('token');
    if (this.token) {
      return this.token;
    }

  },
  login: function (loginInfo, success, fail) {
    console.log(loginInfo);
    axios.post(DOMAIN + '/teacher/login', loginInfo)
      .then(res => {
        if (res.status === 200) {
          this.token = res.data.token_type + ' ' + res.data.access_token;
          if (loginInfo.remember) {
            localStorage.setItem('token', this.token);
          } else {
            sessionStorage.setItem('token', this.token);
          }
          success(res.data.teacher);
        }
      })
  },
  get: function (url, data = {}, success, fail) {

    axios.get(DOMAIN + url + '?' + qs.stringify(data), { headers: { 'Authorization': this.getToken() } })
      .then(res => success(res.data))
  },
  post: function (url, data = {}, success, fail) {
    axios.post(DOMAIN + url, data, { headers: { 'Authorization': this.getToken() } })
      .then(res => success(res.data));
  },
  delete: function (url, success, fail) {
    axios.put(DOMAIN + url, {}, { headers: { 'Authorization': this.getToken() } })
      .then(res => success(res.data))
  },
  put: function (url, data = {}, success, fail) {
    axios.put(DOMAIN + url, data, { headers: { 'Authorization': this.getToken() } })
      .then(res => success(res.data))
  }
}

export default http;